<?php

	include_once("cmsConfig.php");

	define("CMS_ELEMENT_HIDDEN",0);//just a hidden element, these are not parsed//
	define("CMS_ELEMENT_LABEL",1);// hidden element and a text label
	define("CMS_ELEMENT_TEXT",2);// a text box
	define("CMS_ELEMENT_DROPDOWN",3);// a drop down box
	define("CMS_ELEMENT_CHECKBOX",4);// a check box
	define("CMS_ELEMENT_HIDDEN_WITH_LABEL",5);// text with a hidden, not used yet
	define("CMS_ELEMENT_TEXTAREA",6);//a text area
	define("CMS_ELEMENT_UNPARSED_TEXT_LABEL",7);//text that will be displayed but ignored
	define("CMS_ELEMENT_FILE_UPLOAD",8);//a file upload stupid :)
	define("CMS_ELEMENT_CHECKBOX_LIST",9);//a list of check boxes
	define("CMS_ELEMENT_FCKEDIT_TEXT", 10);// a dynamic wysiwyg editor using fck edit.
	define("CMS_ELEMENT_DATE",11);//text box with a calendar to select date	
	define("CMS_ELEMENT_TINYMCE_TEXT",12);//textbox with tiny mc editor
	define("CMS_ELEMENT_UPDATING_LABEL", 13); // this is like a label.. however it will always, when being saved.. be set to its default value.
	define("CMS_ELEMENT_PRIMARY_KEY", 14);// not sure if i need this, or not...
	define("CMS_ELEMENT_DROPDOWN_TREE", 15);// for tree structures
	define("CMS_ELEMENT_KVCID",16);
	define("CMS_ELEMENT_GOOGLE_MAPS",17); //A google map selector (stores coordinates)
	define("CMS_ELEMENT_IMPROVED_CHECKBOX_LIST",18); //A google map selector (stores coordinates)
	define("CMS_ELEMENT_UPDATING_VALUE_LABEL",19);//this is to be used for the document type code, so we dont need to use a bloody dropdown.
	define("CMS_ELEMENT_MULIPLE_KEY_VALUE_PAIRS",20);//this is a many to many that allows you to add many items to a list as key value pairs
	
	
	
	class CmsFormElement {
		
		var $db;
		var $formId ;

		var $elementReader;
		var $optionReader;
		var $formDescriptor;
		var $content;//we use this top populate the form with data..
		
		function CmsFormElement($formDescriptor , $db){

			$this->db = $db;
			$this->formDescriptor = $formDescriptor;
			$this->formId = $this->formDescriptor->formid;
			$this->targetForm = $this->formDescriptor->formname;

			//we use this to read element data..
			$this->elementReader = new CmsTableWriter(CMS_ELEMENT_DESC_FORMAT,$this->db);
		}
		

		function setContent($content){
			$this->content = $content;
		}
		
		function clearContent(){
			$this->setContent(null);
		}
		
		
		function getDefaultFromSource($elementDescriptor){
			$value = null;
			if ($elementDescriptor->sourcequery){
				
				//echo $elementDescriptor->sourcequery;
				
				$this->db->executeQuery(magicClean($elementDescriptor->sourcequery));
				if ($this->db->numRows() > 0 ){
					$row = $this->db->nextRow();
					$value = $row[0];
				}
			} else if (!$value && $elementDescriptor->defaultvalue){
				$value = $elementDescriptor->defaultvalue;
			}
			return $value;		
		}
		
		function getDefaultFromContent($elementDescriptor){
			//we have content.. use that.. as the default
			$value = null;
			if( is_object( $this->content) && isset( $this->content->{ $elementDescriptor->name } )){
				$value = $this->content->{ $elementDescriptor->name };
			}
			
			if (is_array( $this->content) && isset($this->content[ $elementDescriptor->name ])){
				$value = $this->content[ $elementDescriptor->name ];
			}
			return $value;		
		}
		
		function getDefault($elementDescriptor){
			$value = null;
			
			//we always try for content first.. as we have post data to deal with.
			if ( ! ($elementDescriptor->elementtype == CMS_ELEMENT_UPDATING_LABEL
				||
				 $elementDescriptor->elementtype == CMS_ELEMENT_UPDATING_VALUE_LABEL)
			){
				$value = $this->getDefaultFromContent($elementDescriptor);
			}
							
			//change the semantics. optional fields.. should not default
			// this is quite a big change in behaviour.
			if (is_null($value) && $elementDescriptor->requiredfield) {
				$value = $this->getDefaultFromSource($elementDescriptor);	
			}
			
			if (is_string($value)|| is_numeric($value))
				$value = magicClean($value, false );
							
			if (is_string($value) && strlen( $value ) == 0) {
				return null;
			} else {
				return $value;
			}	
		}
		
		function getElementDescriptor($elementId){
			return $this->elementReader->readItem($elementId);
		}
		
		function validateElement($fieldDescription, $value){//this also mangles things so that they fit in the databasss
		
			//echo "VALIDATE ELEMENT>>>>>>>>>";
			//myPrintR ($fieldDescription);
			if ($fieldDescription != null){
				if ($fieldDescription['type'] =='int'){
					// if this is null or false set value to  0, all exprs that evaluate to true 
					// set value to 1// int will allways return true...
					if (is_int($value)){
						$value  =  $value;
					} else if (!$value){
						$value = 0;
					} else {
						$v = (int)$value;
						if ((string)$v == $value){
							$value = $v;
						} else {
							$value = 1;
						}
					}
					return $value;
				} else if ($fieldDescription['type'] == 'varchar'){
					// no long strings..
					if((strlen($value) <= $fieldDescription['length'])){
						return $value;
					} else {
						return false;
					}
				} else if ($fieldDescription['type'] == 'date'||$fieldDescription['type'] == 'datetime'){
					if (is_null($value))
						return $value;
					if ($value == ''){
						$value = null;
						return $value;
					}
					$ret = date("Y-m-d H:i:s", strtotime($value));//what will this return with bungness??? It throws an error message and saves it as though it were today
					if (!$ret){
						return false;					
					} else {
						//$value = $ret;
						//return true;
						return $ret;
					}
				}
				return $value;
			} 
			return false;// we assume that if we have no form description etc.. ignore.
			
		}

		
		function printElement($elementId){
			//get the form data 
			if (!($elementDescriptor = $this->getElementDescriptor($elementId))){
				print("<!-- element $elementId for form $this->formId not found -->");
			} else {
				$elementDescriptor->sourcequery = parseSourceQuery($elementDescriptor->sourcequery);
				switch ($elementDescriptor->elementtype){
					case CMS_ELEMENT_HIDDEN:
						
						/*	with hiddens a query takes precedence over a 
							default value as we can only display one.. unless the query fails,
							these really arent needed, and for security reasons will be overwritten 
							by the add/update script.
						*/
						
						printHidden(
							$elementDescriptor->name,
							processAttribs(	array("value"=>$this->getDefault($elementDescriptor),  'id' => 'cms_form_' . $elementDescriptor->name , 'class'=>'cms_form_hidden' ), array())
						);						
					break;
					case CMS_ELEMENT_PRIMARY_KEY:
					case CMS_ELEMENT_LABEL:
					case CMS_ELEMENT_UPDATING_LABEL:
						//print a label that has no value associated with it..attribs are ignored... 
						print("<span id=\"cms_form_$elementDescriptor->name\" class=\"cms_form_textlabel\" name=\"$elementDescriptor->name\" >" . $this->getDefault($elementDescriptor) . "</span>");
					break;
					
					case CMS_ELEMENT_TEXT:
						// i have added s strreplace to turn " to &quot; .. we only need it for inputs. text areas dont mind.//
						//plain text inputs are treated as is...
						printTextInput(
								$elementDescriptor->name,
							processAttribs(array("value"=>str_replace('"','&quot;', $this->getDefault($elementDescriptor)), 'id' => 'cms_form_' . $elementDescriptor->name , 'class'=>'cms_form_text' ), array())
						);
					break;
					
					case CMS_ELEMENT_IMPROVED_CHECKBOX_LIST:
						$this->db->executeQuery($elementDescriptor->sourcequery);
						$values = array();
						while ($row = $this->db->nextRow()) {
							$values[$row[0]] =  $row[1];
						}
						$checked = null;
						$checked = array();
						$content = (array) $this->content;
						//
						if (isset($content[ $elementDescriptor->name ]) && is_array($content[ $elementDescriptor->name ]) ) {
							$checked = 	(array)$content[ $elementDescriptor->name ];
						} else 
						
						if (isset($content['documentcode'])) {
							$this->db->executeQuery("SELECT relatedcode FROM manytomanydata WHERE parentcode='". $content['documentcode']."' AND elementid = '". $elementDescriptor->elementid ."' ");
							while (($checkRow = $this->db->nextRow())){
								$checked[] = $checkRow[0];
							}							
						}
						printDualCheckBoxList($elementDescriptor->name, $values, $checked );
						?>
						<script language="javascript" type="text/javascript">
						initChecklist();
						</script>
						<?
					break;
					
					case CMS_ELEMENT_GOOGLE_MAPS:
						echo "<a onClick=\"javascript:window.open('/cms/html/Maps/maps.php', 'mapswindow','menubar=0,resizable=0,width=600,height=500');\" href=\"#\">Select Map</a>\n";
						$currentMap = $this->getDefault($elementDescriptor);
						$map_id = null;
						$map_latitude = null;
						$map_longitude = null;
						$map_altitude = null;
						$map_address = null;
						$map_markertext = null;
						if ($currentMap) {
							$this->db->executeQuery("SELECT id, latitude, longitude, altitude, address, markertext FROM googlemaps WHERE id='".$currentMap."'");
							if ($row = $this->db->nextRow()) {
								$map_id = $row[0];
								$map_latitude = $row[1];
								$map_longitude = $row[2];
								$map_altitude = $row[3];
								$map_address = $row[4];
								$map_markertext = $row[5];
							}
						}
						echo "<input type=\"hidden\" name=\"".$elementDescriptor->name."[id]\" value=\"".$map_id."\">";
						echo "<input type=\"hidden\" name=\"".$elementDescriptor->name."[latitude]\" value=\"".$map_latitude."\">";
						echo "<input type=\"hidden\" name=\"".$elementDescriptor->name."[longitude]\" value=\"".$map_longitude."\">";
						echo "<input type=\"hidden\" name=\"".$elementDescriptor->name."[altitude]\" value=\"".$map_altitude."\">";
						echo "<input type=\"hidden\" name=\"".$elementDescriptor->name."[address]\" value=\"".$map_address."\">";
						echo "<input type=\"hidden\" name=\"".$elementDescriptor->name."[markertext]\" value=\"".$map_markertext."\">";
					break;
					
					case CMS_ELEMENT_DATE:
						echo "<div class=\"cms_form_date\">";
						printDateInput(
							$elementDescriptor->name, 
							processAttribs(array("value"=>$this->getDefault($elementDescriptor), 'id' => 'cms_form_' . $elementDescriptor->name , 'class'=>'cms_form_date'),array())
						);
						echo "</div>";
					break;			
							
					case CMS_ELEMENT_DROPDOWN:
					
						/*	with the option lists, we have a query that fills the list, 
							the first col is the value and the second col is the label/text,
							if a default is provided then we will use javascript to
							set the form to this..
						*/
						$elementDefault = $this->getDefault($elementDescriptor);

						optionList(
							processAttribs(
								array("name"=>$elementDescriptor->name) ,array( 'id' => 'cms_form_' . $elementDescriptor->name , 'class'=>'cms_form_dropdown' ) ),
								!$elementDescriptor->requiredfield,
								$elementDefault ,
								0,
								1,
								$elementDescriptor->sourcequery,
								$this->db
						);
//add the javascript here..

					break;
					case CMS_ELEMENT_UPDATING_VALUE_LABEL:
						//run the source query..
						$objects = $this->db->getAllAsArray($elementDescriptor->sourcequery,($a = array()));
						if (1 == count($objects)) {
							$value = $objects[0];
							print("<span id=\"cms_form_$elementDescriptor->name\" class=\"cms_form_textlabel\" name=\"$elementDescriptor->name\" >" . $value[1] . "</span>");						
						}
						//
					break;
					
					/*  THIS WAS THE GENERIC STUFF APRA STUFF HAS BEEN ADDED BELOW.
					
					case CMS_ELEMENT_DROPDOWN_TREE:
					
						/*	with the option lists, we have a query that fills the list, 
							the first col is the value and the second col is the label/text,
							if a default is provided then we will use javascript to
							set the form to this..
						*//*
						
						//Oh God of code here we go!
						//pull out the query into an array or stack
						$dbarray = array();
						//$detailsArray = array();
						//begin select output
						$output = "<select name=\"$elementDescriptor->name\" id=\"'cms_form_" . $elementDescriptor->name. "\" class=\"cms_form_dropdown\" >\n";
						$output .= "<option value=\"-1\">Not In Menu</option>\n";
						$output .= "<option value=\"0\">Top Level</option>\n";
						
						if ($this->db->canExecuteQueries() && 
							$this->db->executeQuery(magicClean($elementDescriptor->sourcequery, 0)) && 
								($this->db->numRows() > 0)) {
								
							while (($row = $this->db->nextAssoc())){
								//echo "<br>result =<pre>"; print_r($row); echo "</pre>";
								//$dbarray[$row[0]] = $row;
								array_push($dbarray, $row);
							}
							$tree= array();
							//foreach ($dbarray as $value) { 
							//
							//}

							$tree = createTreeFromNodes( $dbarray);
							
							//echo "<br>treelist =<pre>"; print_r($tree); echo "</pre>";
							
							$outarray = array();
							$outarray = preordNodeListFromTree($tree[0]);
							
							//echo "<br>finallist =<pre>"; print_r($outarray); echo "</pre>";
							
							
							$parentList = array();
							
							foreach ($outarray as $value) {
								//okay want to put value[value] onto parent stack echo it out then remove it and any others as 
								//necessary
								while ($parentList[0][0] != $value[parent]) {
								//if($parentList[0][0] != $value[parent]) {
									//remove from parentList
									array_shift($parentList);
									//echo "count";
									if($value[parent] == 0) {
										$parentList = array();
										break;
									}
								}
								//echo "parent = ". $value[parent]. " parentList = ". $parentList[0][0]. "<br>";
								array_unshift($parentList, array($value[id], $value[value]));
								$output .= "<option value=\"" . $value[id] . "\">";
								$reverseParentList = array_reverse($parentList);
								foreach ($reverseParentList as $text) {
									$output .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
								}
								$output .= $value[value];
								$output .= "</option>\n";
							}
							
							//echo "parents = <pre>";print_r($parentList);echo "</pre>";
						} //else {
							//$optionRoot->addChild("option","N/A",array("value"=>""));			
						//}
						
						$output .= "</select>\n";
						echo $output;
						
						//add the javascript here..
						$elementDefault = $this->getDefault($elementDescriptor);
							
							print <<< EOD
<script>
        for (i=0; i < document.forms['$this->targetForm'].elements['$elementDescriptor->name'].options.length; i++){
                if(document.forms['$this->targetForm'].elements['$elementDescriptor->name'].options[i].value=='$elementDefault'){
                        document.forms['$this->targetForm'].elements['$elementDescriptor->name'].selectedIndex=i;
                }
        }
</script>							
EOD;
						
					break;*/
					
					case CMS_ELEMENT_DROPDOWN_TREE:
					
						/*	with the option lists, we have a query that fills the list, 
							the first col is the value and the second col is the label/text,
							if a default is provided then we will use javascript to
							set the form to this..
						*/
						
						function printTreeSelect($node, $expandMenu=false, $depth=0) {
							$tabs = "";
							for ($i=0; $i< $depth; $i++){
								$tabs .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
							}
							
							if ( !is_null($node['children']) && is_array($node['children']) )
								usort($node['children'], "noderanksort");
								
							foreach ( $node['children'] as $key  => $value) {
								$hasChildren = (key_exists('children', $value) && count($value['children']) > 0 );
								echo "<option value=\"" . $value["id"] . "\">$tabs"  . $value["value"]. "</option><br/>";
								if ($hasChildren) {
									echo "\n";
									printTreeSelect($value, $expandMenu, $depth + 1);
								}
								echo "\n";
							}
						}
							
						$tree = getMenuTree($this->db);
						echo "<select name=\"$elementDescriptor->name\" id=\"'cms_form_" . $elementDescriptor->name. "\" class=\"cms_form_dropdown\" >\n";
						echo "<option value=\"-1\">Not In Menu</option>\n";
						echo "<option value=\"0\">Top Level</option>\n";
						printTreeSelect($tree[0], false);
						echo "</select>\n";
						
						//add the javascript here..
						$elementDefault = $this->getDefault($elementDescriptor);
							
							print <<< EOD
<script>
        for (i=0; i < document.forms['$this->targetForm'].elements['$elementDescriptor->name'].options.length; i++){
                if(document.forms['$this->targetForm'].elements['$elementDescriptor->name'].options[i].value=='$elementDefault'){
                        document.forms['$this->targetForm'].elements['$elementDescriptor->name'].selectedIndex=i;
                }
        }
</script>							
EOD;
						
					break;
					
					
					case CMS_ELEMENT_CHECKBOX:
						//printCheckBox($elementDescriptor->name,processAttribs(array("value"=>'1', 'id' => 'cms_form_' . $elementDescriptor->name , 'class'=>'cms_form_checkbox'),array()));
						echo jsDualStateCheckBox($elementDescriptor->name,1,0,$this->getDefault($elementDescriptor));
					break;
					
					case CMS_ELEMENT_HIDDEN_WITH_LABEL:
						// write me when i am needed.. not really needed..
					break;
					
					case CMS_ELEMENT_TEXTAREA:
						//we dont need to actually.. um.. need to .. quote here.
						/*	create a text area
						*/
						printTextArea($elementDescriptor->name,$this->getDefault($elementDescriptor),processAttribs(  array('id' => 'cms_form_' . $elementDescriptor->name , 'class'=>'cms_form_textarea'), array()));
						//$formName = $this->targetForm;
						//$elementName = $elementDescriptor->name;
						
					break;
					
					case CMS_ELEMENT_UNPARSED_TEXT_LABEL:
						print("<span id=\"cms_form_$elementDescriptor->name\" class=\"cms_form_up_textlabel\" name=\"$elementDescriptor->name\" >" . $this->getDefault($elementDescriptor) . "</span>");
					break;
					
					case CMS_ELEMENT_FILE_UPLOAD:
						
						//we will also add a little preview if the object is an image :) or
						// a link to the object otherwise
						
						//need to get the info to switch on.
						$isBinaryCopy = true;
						$binaryFileId = null;
						$binaryElementId = null;
						$binaryDocumentCode = null;

						if ( is_object($this->content[ $elementDescriptor->name ]) ) {
							$binaryElementId = $this->content[ $elementDescriptor->name ]->elementid;							
							$binaryDocumentCode = $this->content[ $elementDescriptor->name ]->documentcode;	
							$binaryFileId =	$this->content[ $elementDescriptor->name ]->id;													
						} else if (	is_object($this->content[ $elementDescriptor->name ]) ) {
							$binaryElementId = $this->content->{ $elementDescriptor->name }->elementid;							
							$binaryDocumentCode = $this->content->{ $elementDescriptor->name }->documentcode;
							$binaryFileId =	$this->content->{ $elementDescriptor->name }->id;						
						} else if (isset($this->content->documentcode)){
							$binaryDocumentCode = $this->content->documentcode;
							$binaryElementId = $elementId;
							$binaryFileId = $this->getDefault($elementDescriptor);
							$isBinaryCopy = false;
						}
						
						if ($isBinaryCopy) {
							print <<< EOD
<input type="hidden" name="$elementDescriptor->name" value="$binaryDocumentCode,$binaryFileId,$binaryElementId" />
EOD;
						}
												
						$binaryRow = null;
						$query = "SELECT * FROM binarydata WHERE id = '".$binaryFileId."' and documentcode='".$binaryDocumentCode."' and elementid='".$binaryElementId."'";
						$this->db->executeQuery($query);

						if ($this->db->numRows() > 0 ) {

							echo "<div class=\"cms_form_file_container\" id=\"cms_fom_filedetails_$elementDescriptor->name\" >";
							
							if ($isBinaryCopy){
								echo "<span class=\"cms_error\" >If no file is uploaded data data will be copied from the following file</span>";	
							}			
							while (($binaryRow = $this->db->nextRow())) {
															
								$mimetype = $binaryRow[6];
								$filesize = $binaryRow[5];
								$filename = $binaryRow[7];
								$filetypecode =$binaryRow[3];
								
								echo "<table><tr><td>";
								if (in_array($mimetype , array("image/pjpeg","image/gif","image/jpeg","image/png","image/x-png" ) )) {

									print("<div class=\"wrap1\"><div class=\"wrap2\"><div class=\"wrap3\"><img class=\"cms_form_file_image\" type=\"" . $mimetype . "\" src=\"/html/blob.php?scale=1&width=90&height=90&document=" . $binaryDocumentCode . "&filetypecode=1&fileId=".$binaryFileId. "&foo=" . md5( "slartybartfast" .(microtimeFloat() % microtimeFloat()) )."\"></div></div></div>");
								}
								else if ($mimetype == "video/x-flv") {
									print("<a class=\"cms_form_file_filelink\" target=\"_blank\" href=\"/html/video.php?documentCode=" . $binaryDocumentCode . "&elementId=".$binaryElementId."&filetypecode=2&foo=" . md5( "slartybartfast" .(microtimeFloat() % microtimeFloat()) )."\" >" . $filename . "</a><br><br>");
								}
								else {
									print("<a class=\"cms_form_file_filelink\" target=\"_blank\" href=\"/html/blob.php?attach=true&documentCode=" . $binaryDocumentCode ."&elementId=".$binaryElementId. "&foo=" . md5( "slartybartfast" .(microtimeFloat() % microtimeFloat()) )."\" >" . $filename . "</a><br><br>");
								}
								echo "</td>";
	
								echo "<td>";
								print <<< EOD
								Document Code = $binaryDocumentCode<br />
								File Id = $binaryFileId<br />
								File Name = $filename<br />
								Mime Type = $mimetype<br />
								Size = $filesize bytes<br />
EOD;
								echo "</td>";
								echo "</tr></table>";								
							}

							echo "</div>";
		
							// check for content.. and allow to remove images if okay to do so...
							if ($this->db->numRows() > 0  && !$elementDescriptor->requiredfield && !$isBinaryCopy) {//cant remove copies..
								print <<< EOD
									<div class="cms_form_file_delete" id="cms_fom_deletefile_$elementDescriptor->name" class="cms_form_file">
										<a class="cms_form_file_delete" href="#" onclick="javascript:goDeleteBinaryDataInDocumentForElement('$binaryDocumentCode','$binaryElementId');">Delete Image</a>
									</div>
EOD;
							}						
						}

						printFileUploadBox($elementDescriptor->name,processAttribs( array( 'id' => 'cms_form_' . $elementDescriptor->name , 'class'=>'cms_form_file'), array()));
					break;
					
					case CMS_ELEMENT_CHECKBOX_LIST:
					
						//generate an array of the check boxes to check.
						$checked = null;
						$checked = array();
						$content = (array) $this->content;
						//
						if (isset($content[ $elementDescriptor->name ]) && is_array($content[ $elementDescriptor->name ]) ) {
							$checked = 	(array)$content[ $elementDescriptor->name ];
						} else 
						
						if (isset($content['documentcode'])) {
							$this->db->executeQuery("SELECT relatedcode FROM manytomanydata WHERE parentcode='". $content['documentcode']."' AND elementid = '". $elementDescriptor->elementid ."' ");
							while (($checkRow = $this->db->nextRow())){
								$checked[] = $checkRow[0];
							}							
						}
						//checkBoxList($elementDescriptor->name,magicClean($elementDescriptor->sourcequery, 0), $this->db, $checked);
						//what the fuxxx0r
						selectBoxList($elementDescriptor->name,magicClean($elementDescriptor->sourcequery, 0), $this->db, $checked, $this->targetForm, processAttribs( array( 'id' => 'cms_form_' . $elementDescriptor->name , 'class'=>'cms_form_dualselect'), array()) );						
						
						
					break;
					
					case CMS_ELEMENT_FCKEDIT_TEXT:
					case CMS_ELEMENT_TINYMCE_TEXT:
						echo tinyMceEditorWithIdAndContent($elementDescriptor->name,$this->getDefault($elementDescriptor), ($hack = array( "inputClass" =>"cmsMailoutBodyContentBlockTextArea" )) );
					break;

					case CMS_ELEMENT_MULIPLE_KEY_VALUE_PAIRS:
					
						//this is going to be slightly not nice..
						
						echo "<ul id=\"cms_form_$elementDescriptor->elementid\" class=\"cms_from_multiple_kvc\">";
						//get the selected keyvalue parirs..
						
						// we are going to print out a list of 
						
						// to print this element.. we generate a source query. where we look up
						// all of the items from the kvpair table and .. print them in a ul..
						//echo $content['documentcode']
						$content = (array)$this->content;
						//if we have posted.. we need to some how passin/deal with the new values..
							//myPrintR($content);
							//myPrintR($_POST);
							$objects = array();
							if ( isset( $content[ 'kvp_key_' . $elementDescriptor->elementid ]) && 
								0 < count( $content[ 'kvp_key_' . $elementDescriptor->elementid ]) &&
								isset( $content[ 'kvp_value_' . $elementDescriptor->elementid ]) && 
								0 < count( $content[ 'kvp_value_' . $elementDescriptor->elementid ]) &&	
								count( $content[ 'kvp_value_' . $elementDescriptor->elementid ]) == count( $content[ 'kvp_key_' . $elementDescriptor->elementid ])					
							){
								$objects = array();
								foreach( $content[ 'kvp_key_' . $elementDescriptor->elementid ] as $key => $keyValue){
									$o = new stdClass();
									$o->key = $keyValue;
									$o->value = $content[ 'kvp_value_' . $elementDescriptor->elementid ][$key];
									$objects[$key] = $o;
								}

							} else {//source query..
								
								if (isset($content['documentcode']) && 0 < $content['documentcode'] ){
									$query = "SELECT * FROM multiplekeyvaluepairs WHERE documentcode = ?";
									$vals = array($content['documentcode']);
									$objects = $this->db->getAllAsObjects($query, $vals);
								}
							}
							
						//	while ($row = $this->db->nextObject()){
							foreach ( $objects as $row )	{
								echo "<li>";
								echo "<input name=\"kvp_key_" . $elementDescriptor->elementid .  "[]\" value=\"$row->key\"/> <input name=\"kvp_value_" . $elementDescriptor->elementid . "[]\" value=\"$row->value\"/>" .
								" <a rel=\"removeKeyValuePair\" href=\"#\" >-</a>" ;
								echo "</li>";	
												
							}
						
						
						?>

<li>
<a rel="insertKeyValuePair" href="#" >+</a>
</li>

<?php
						echo "</ul>";
?>
<script type="text/javascript" language="javascript">
	//first we need to check if this code has been included or not.. we will take a yui approach.. sort of here.
	
	if ( typeof Gravitate.MultipleKeyValuePair == 'undefined')  {
		
		Gravitate.MultipleKeyValuePair = {
			insertKeyValuePair: function (e){
				//var n =  e.target.parentNode.parentNode;
				var elementId = e.target.parentNode.parentNode.id.substring("cms_form_".length);
				
				//cms_form_$elementDescriptor->elementid
				var li = new Element('li');
				li.insert(
					new Element ('input',{
						name: "kvp_key_" + elementId + "[]"
					})
				);
				li.insert(' ');
				li.insert(
					new Element ('input',{
						name: "kvp_value_" + elementId + "[]"
					})
				);
				li.insert(' ');
				li.insert(
					new Element('a',{rel: "removeKeyValuePair", href: "#"}).update("-")
				);
				
				e.target.parentNode.insert({before: li});
						
			},
			removeKeyValuePair: function (e){
				//alert("remove " + e.target.parentNode.id);
				var n =  e.target.parentNode;
				n.remove();
			}
		};
		
		document.observe('click', function(e){
			//alert(e);
			if (e.target.rel=='removeKeyValuePair') {
				Gravitate.MultipleKeyValuePair.removeKeyValuePair(e);
				e.stop();				
			}
			if (e.target.rel=='insertKeyValuePair') {
				Gravitate.MultipleKeyValuePair.insertKeyValuePair(e);
				e.stop();				
			} 
		});
	}
</script>
<?php

					break;
					
					default:
					break;
				}
			}
		}
		
}

